package com.yjc.blog.service.impl;

import com.baomidou.mybatisplus.core.toolkit.support.BiIntFunction;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yjc.blog.domain.bo.UserBo;
import com.yjc.blog.domain.bo.UserLoginBO;
import com.yjc.blog.domain.bo.UserSave;
import com.yjc.blog.domain.po.User;
import com.yjc.blog.domain.vo.PageVO;
import com.yjc.blog.domain.vo.UserLoginVO;
import com.yjc.blog.domain.vo.UserVO;
import com.yjc.blog.mapper.UserMapper;
import com.yjc.blog.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjc.blog.utils.CopyUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yjc
 * @since 2024-11-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Override
    public PageVO<UserVO> userList(UserBo dao) {
        boolean isUseEmpty = (dao.getName() == null && dao.getLoginName() == null);
        List<User> list = new ArrayList<>();
        PageHelper.startPage(dao.getPage(),dao.getSize());
        if (isUseEmpty){
            list = this.list();

        }else {
             list = this.lambdaQuery()
                    .eq(dao.getLoginName() != null, User::getLoginName, dao.getLoginName())
                    .or()
                    .eq(dao.getName() != null, User::getName, dao.getName())
                    .list();
        }
        PageInfo<UserVO> info = new PageInfo<>();
        List<UserVO> vos = CopyUtil.copyList(list, UserVO.class);
        PageVO<UserVO> pageVO = new PageVO<>();
        pageVO.setTotal(info.getTotal());
        pageVO.setList(vos);
        return pageVO;
    }

    @Override
    public void userDelete(Long id) {
        this.removeById(id);
    }

    @Override
    public void userSave(UserSave save) {
        User user = CopyUtil.copy(save, User.class);
        if (save.getId() == null){
            this.save(user);
        }
        else {
            this.lambdaUpdate()
                    .eq(User::getId,save.getId())
                    .update(user);
        }
    }
//    public void selectByLoginName(String name){
//        this.lambdaQuery()
//                .eq(User::getLoginName,name){
//
//        }
//    }

    @Override
    public UserLoginVO login(UserLoginBO bo) {
        if (bo.getLoginName().isEmpty()){
            //todo 用户不存在抛出异常
            throw new IllegalArgumentException();
        }
        else {
            User user = this.lambdaQuery()
                    .eq(User::getLoginName, bo.getLoginName())
                    .one();
            if (user.getPassword().equals(bo.getPassword())){
                UserLoginVO vo = CopyUtil.copy(user, UserLoginVO.class);
                return vo;
            }else {
                //todo 密码正确抛出异常
                throw new RuntimeException();
            }
        }
    }
}
